package org.vector.pefind.elfinder.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * 因为在mvc.xml中配置的CommonsMultipartResolver与elFinder的文件上传有冲突 所以这是非elfinder上传文件的实现
 * 
 * @author mjp
 */
@Controller
@RequestMapping("upload")
public class FileUploadController extends MultiActionController {
	String uploadFolder = "upload";

	/**
	 * 一个普通的提交文件上传的form：web/upload/myown
	 * @param req
	 * @param res
	 * @throws ServletException
	 * @throws IOException
	 * @throws FileUploadException
	 */
	@RequestMapping(value = "myown", method = RequestMethod.POST)
	public void myown(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException, FileUploadException {

		CommonsMultipartResolver cmr = new CommonsMultipartResolver(req.getSession().getServletContext());
		PrintWriter pw = res.getWriter();
		String callback = req.getParameter("CKEditorFuncNum");
		System.out.println("callback => "+callback);
		

		// 判断是否是上传请求
		if (!cmr.isMultipart(req)) {
			System.out.println("err ---1");
		}
		System.out.println("ok ---1");

		// 是文件上传则转换请求类型：
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;

		//获取所有文件名
		Iterator<String> it = mreq.getFileNames();

		// 单文件
		MultipartFile file = mreq.getFile(it.next());
		String fileName = file.getOriginalFilename();//上传原文件名,等会改文件名试试看
		
		if(!(fileName.endsWith(".jpg") || fileName.endsWith(".gif") || fileName.endsWith(".bmp") || fileName.endsWith(".png"))){
			pw.println("<script type=\"text/javascript\">");    
			pw.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");   
			pw.println("</script>");
		}
		
		File uploadFile = new File(req.getSession().getServletContext().getRealPath(uploadFolder));

		if (!uploadFile.exists() && !uploadFile.isDirectory()) {
			uploadFile.mkdir();
		}

		File photoFile = new File(uploadFile, fileName);

		try {
			file.transferTo(photoFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
